package cnt5106.p2p.peer.peerhandler;

import java.net.Socket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import cnt5106.p2p.common.protocol.Message;
import cnt5106.p2p.common.protocol.MessageType;
import cnt5106.p2p.peer.filesystem.FileControler;


public class MessageHandler 
{
	FileControler fc = null;
	InetSocketAddress tcpAddr = null;
	
	public MessageHandler (FileControler fc, int port) throws UnknownHostException
	{
		this.fc = fc;
		tcpAddr = new InetSocketAddress(InetAddress.getLocalHost(), port);
	}
	
	public Object msParse(Message msg) throws IOException
	// return a message, a socket or null
	{
		MessageType rcType = msg.getType();
		String fname = msg.getFilename();
		int chunkNum = msg.getNumber();
		byte[] data = (byte[]) msg.getData();
		
		switch (rcType) {
		case PEER_REQUEST_CHUNK:
			if ((data = fc.readFile(chunkNum, false)).equals(null))
				return Message.generate(MessageType.PEER_POSITIVE_REPLY, fname, msg.getNumber(), data);
			else
				return Message.generate(MessageType.PEER_NEGATIVE_REPLY, fname, msg.getNumber(), "");
		case PEER_POSITIVE_REPLY:
		case PEER_FILEOWNER_DATAPACKET:
			fc.writeFile(data, chunkNum);
			break;
		case PEER_NEGATIVE_REPLY:
			break;
		case PEER_FILEOWNER_END:
			/////////shut down the tcp connection, but how?/////////
			break;
		case PEER_TCPPORT_REQUEST:
			return Message.generate(MessageType.PEER_TCPPORT_REPLY, "", 0, tcpAddr);
			//generate(type, filename, number, data)
		case PEER_TCPPORT_REPLY:
			if (msg.getData() instanceof InetSocketAddress){
				InetSocketAddress addr = (InetSocketAddress)msg.getData();
				return new Socket(addr.getAddress(), addr.getPort());
			}
			else
				return null;
		}
		return null;
	}	
}
